package com.wfcm.wxPay;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup; 
import org.jsoup.nodes.Document;

import com.alibaba.fastjson.JSONObject;
import  com.wfcm.wxPay.WXUtil;
import com.wfcm.utils.ConstantUtil;
import com.wfcm.utils.XMLUtil;
import com.wfcm.wxPay.PayRefundVo;

/**
 * 生成预支付订单号
 * 
 * @author Sunlight
 *
 */
public class WXTestpay {
    private static String testUrl = "https://apitest.mch.weixin.qq.com/sandboxnew/pay/getsignkey";
    private String mch_id;
    private String nonce_str = WXUtil.getNonceStr();
    private String sign;
    
    /**
     * 生成预支付订单
     * 
     * @return
     */
    public String submitXmlGetPrepayId() {
        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        HttpPost httpPost = new HttpPost(testUrl);
        String xml = getTestPackage();
        StringEntity entity;
        try {
            entity = new StringEntity(xml, "utf-8");
            httpPost.setEntity(entity);
            HttpResponse httpResponse;
            // post请求
            httpResponse = closeableHttpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                // 打印响应内容
                String result = EntityUtils.toString(httpEntity, "UTF-8");
                System.out.println(result);
                // 过滤
                result = result.replaceAll("<![CDATA[|]]>", "");
                return result;
            }
            // 释放资源
            closeableHttpClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "***测试***";
    }

    
    public static void main(String[] args) throws Exception {
        String partner = ConstantUtil.PARTNER;
        WXTestpay testPay = new WXTestpay();
        testPay.setMch_id(partner);
        
        String pack = testPay.submitXmlGetPrepayId();
        
        System.out.println(JSONObject.toJSON(pack));
    }
    
    public String getTestPackage() {
        TreeMap<String, String> treeMap = new TreeMap<String, String>();
        treeMap.put("mch_id", this.mch_id);
        treeMap.put("nonce_str", this.nonce_str);
        StringBuilder sb = new StringBuilder();
        for (String key : treeMap.keySet()) {
            sb.append(key).append("=").append(treeMap.get(key)).append("&");
        }
        sb.append("key=" +  ConstantUtil.PARTNER_KEY);
        sign = MD5Util.MD5Encode(sb.toString(), "utf-8").toUpperCase();
        treeMap.put("sign", sign);
        StringBuilder xml = new StringBuilder();
        xml.append("<xml>\n");
        for (Map.Entry<String, String> entry : treeMap.entrySet()) {
            if ("body".equals(entry.getKey()) || "sign".equals(entry.getKey())) {
                xml.append("<" + entry.getKey() + "><![CDATA[").append(entry.getValue())
                        .append("]]></" + entry.getKey() + ">\n");
            } else {
                xml.append("<" + entry.getKey() + ">").append(entry.getValue()).append("</" + entry.getKey() + ">\n");
            }
        }
        xml.append("</xml>");
        System.out.println("\n\ngetPackage" + xml.toString());
        return xml.toString();
    }
    
    /**
	 * 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
	 */
	public static String createSign(SortedMap<String, String> packageParams, String AppKey) {
		StringBuffer sb = new StringBuffer();
		Set es = packageParams.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + AppKey);
		System.out.println("sb="+sb.toString());
		String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
		return sign;
	}

	public String getMch_id() {
		return mch_id;
	}
	public void setMch_id(String mch_id) {
		this.mch_id = mch_id;
	}
	public String getNonce_str() {
		return nonce_str;
	}
	public void setNonce_str(String nonce_str) {
		this.nonce_str = nonce_str;
	}
	public String getSign() {
		return sign;
	}
	public void setSign(String sign) {
		this.sign = sign;
	}

}
